package logic

import (
	"baidutieba/models/cache"
	"baidutieba/models/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"baidutieba/tiebarpc/internal/svc"
	"baidutieba/tiebarpc/tiebarpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TiebaHotListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTiebaHotListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TiebaHotListLogic {
	return &TiebaHotListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TiebaHotListLogic) TiebaHotList(in *tiebarpc.TiebaHotListRequest) (*tiebarpc.TiebaHotListResponse, error) {
	// todo: add your logic here and delete this line
	var hot []mysql.TieBa
	key := fmt.Sprintf("hotList")
	get, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if get == "" {
		mysql.DB.Debug().Limit(10).Order("num desc").Find(&hot)
		marshal, _ := json.Marshal(&hot)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*2)
	} else {
		json.Unmarshal([]byte(get), &hot)
	}

	var hotlist []*tiebarpc.TieHotList
	for _, ba := range hot {
		lists := tiebarpc.TieHotList{
			Title:   ba.Title,
			Image:   ba.Image,
			Num:     ba.Num,
			UserId:  ba.UserId,
			Context: ba.Context,
			Class:   ba.Class,
		}
		hotlist = append(hotlist, &lists)
	}
	return &tiebarpc.TiebaHotListResponse{
		List: hotlist,
	}, nil
}
